<template>
  <el-row class="mx__20 px-20 bg-white">
    <el-col class="current-content-style">
      <el-row class="py-20">
        <el-col :span="24">
          <el-descriptions class="margin-top" title="水表信息" :column="2" size="medium" border>
            <template slot="extra">
              <el-button @click="isShowAssociated = true">添加联系人</el-button>
              <el-button @click="showEditWaterMeterModal">编辑水表</el-button>
            </template>
            <el-descriptions-item label="开户合同">
              <a v-if="waterInfo.waterContractPath" target="_blank" :href="this.imgUrl + waterInfo.waterContractPath"
                >查看合同</a
              >
              <router-link v-else-if="waterInfo.customerId" :to="'/home/customedetail?id=' + waterInfo.customerId"
                >去上传合同</router-link
              >
              <span v-else>未绑定的水表</span>
            </el-descriptions-item>
            <el-descriptions-item label="开户人员">{{ waterInfo.customerName }}</el-descriptions-item>
            <el-descriptions-item label="水表编号">{{ waterInfo.waterNumber }}</el-descriptions-item>
            <el-descriptions-item label="水表类型">{{ waterInfo.waterModel }}</el-descriptions-item>
            <el-descriptions-item label="计费类型">{{ waterInfo.billingName }}</el-descriptions-item>
            <el-descriptions-item label="最大计量">{{ waterInfo.waterMaxMeter }}吨</el-descriptions-item>
            <el-descriptions-item label="初始读数">{{ waterInfo.waterInitialCount }}吨</el-descriptions-item>
            <el-descriptions-item label="安装日期">{{
              getUserFormatDate(waterInfo.waterInstallTime)
            }}</el-descriptions-item>
            <el-descriptions-item label="安装地址">{{
              waterInfo.waterInstallAddress
                ? waterInfo.waterInstallAddress + '-' + waterInfo.waterInstallAddressInfo
                : '空'
            }}</el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>
      <el-row type="flex" class="bg-layer-body mt-20">
        <el-table :data="waterInfo.associatedList" style="width: 100%">
          <el-table-column prop="associatedName" label="已关联水表人员" width="180"> </el-table-column>
          <el-table-column prop="associatedPhone" label="电话号码" width="180"> </el-table-column>

          <el-table-column label="操作">
            <template v-slot="scope">
              <el-button type="text" @click="dissociatedHandle(scope.row)">解除关联</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-row class="mt-20 py-20">
        <el-col :span="24" class="text-center">
          <el-button class="btn-back" type="primary" @click="$router.push('/home/waterqualitymg')">返回</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col> </el-col>
      </el-row>
    </el-col>
    <el-dialog title="添加联系人" :visible.sync="isShowAssociated" width="30%">
      <el-form ref="addform" :model="addAssociatedForm" :rules="rulesAddForm" label-width="120px">
        <el-form-item label="联系人名称" prop="associatedName">
          <el-input v-model="addAssociatedForm.associatedName"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="associatedPhone">
          <el-input v-model="addAssociatedForm.associatedPhone"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowAssociated = false">取 消</el-button>
        <el-button type="primary" @click="addAssociatedHandler('addform')">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="编辑水表" :visible.sync="isShowEditWaterMeter" width="50%">
      <el-form ref="editform" :model="editForm" :rules="rulesEditWaterMeterForm" label-width="120px">
        <el-form-item label="计费类型" prop="billingId ">
          <el-select v-model="editForm.billingId" placeholder="请选择计费类型">
            <el-option
              v-for="item in billingType"
              :key="item.billingId"
              :label="item.billingName"
              :value="item.billingId"
            >
            </el-option>
          </el-select>
          <span class="px-20 text-success">价格：{{ getCheckBillingPrice }} 元/吨</span>
        </el-form-item>
        <!-- <el-form-item label="安装地址" prop="address">
          <el-input v-model="editForm.address"></el-input>
        </el-form-item> -->
        <el-form-item label="安装地址" prop="waterInstallAddress">
          <el-cascader
            style="width: 220px"
            ref="cascader"
            v-model="checkedAddessValues"
            :options="data"
            :props="addressProps"
            clearable
            size="mini"
            separator="-"
            placeholder="请选择"
            :show-all-levels="true"
            @expand-change="handleCheck"
            @change="handleChange"
          ></el-cascader>
          <span class="px-20">{{ editForm.waterInstallAddress }}</span>
        </el-form-item>
        <el-form-item label="安装详细地址" prop="waterInstallAddressInfo">
          <el-input v-model="editForm.waterInstallAddressInfo" style="width: 220px"></el-input>
        </el-form-item>
        <el-form-item label="变更原因" prop="changeInfo ">
          <el-input type="textarea" v-model="editForm.changeInfo"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowEditWaterMeter = false">取 消</el-button>
        <el-button type="primary" @click="editEditWaterHandler('editform')">确 定</el-button>
      </span>
    </el-dialog>
  </el-row>
</template>

<script>
// 仪表详细
import {
  getWaterMeterDetailInfo,
  addAssociated,
  disAssociated,
  queryRootRegionAll,
  queryChildrenRegionAll,
  getBilingBasePriceNotPage,
  editWaterMeterInfo
} from '@/config/api'
import { getUserFormatDate } from '@/utils/dateUtils'
export default {
  created() {
    // console.log(this.$route)
    this.waterNumber = this.$route.query?.waterNumber

    this.getWaterMeterDetail()
    this.queryRootRegionAllHandler()
    this.getBillingTypeHandler()
  },
  data() {
    return {
      isShowAssociated: false,
      isShowEditWaterMeter: false,
      // 计费类型数组
      billingType: [],
      // 添加联系人的from
      addAssociatedForm: {
        associatedName: '',
        associatedPhone: ''
      },
      // 修改水表的form对象
      editForm: {
        billingId: '',
        waterInstallAddress: '',
        waterInstallAddressInfo: '',
        changeInfo: '',
        customerAddress: ''
      },
      waterNumber: '',
      waterId: '',
      waterInfo: {},
      // 添加水表联系人的规则
      rulesAddForm: {
        associatedName: [
          { required: true, message: '请输入中文名称', trigger: 'blur' },
          {
            pattern: /^[\u4E00-\u9FA5]{1,20}$/,
            message: '只能输入汉字1-20个',
            trigger: 'blur'
          }
        ],
        associatedPhone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: '请输入11位数字',
            trigger: 'blur'
          }
        ]
      },
      // 编辑水表form的规则
      rulesEditWaterMeterForm: {
        billingId: [{ required: true, message: '请选择计费类型', trigger: 'change' }],
        waterInstallAddress: [{ required: true, message: '请选择地址', trigger: 'change' }],
        waterInstallAddressInfo: [{ required: true, message: '请选择地址', trigger: 'change' }],
        changeInfo: [{ required: true, message: '请输入变更原因', trigger: 'blur' }]
      },
      // 三级联动的props配置
      addressProps: {
        expandTrigger: 'click',
        value: 'id', // 多级选择器的option项的value对应数据中的id属性
        label: 'regionName', // 多级选择器的option项的label对应数据中的regionName属性
        lazy: true,
        lazyLoad: this.loadNode
      },
      level_1: [], //存储请求回来的1级地域
      checkedKeys: [], // 选择的地域id
      data: [], //root 地域数组
      checkedAddessValues: [] // 选择的地域名称
    }
  },
  computed: {
    getCheckBillingPrice() {
      let billingPrice = null
      this.billingType.forEach(el => {
        if (el.billingId === this.editForm.billingId) {
          billingPrice = el.billingPrice
        }
      })
      // console.log(billingPrice)
      return billingPrice
    }
  },
  watch: {
    checkedAddessValues(val) {
      // console.log('checkedAddessValues', val)
      this.checkedKeys = val
      // 获取到选择的节点数组对象
      let arr = this.$refs.cascader.getCheckedNodes()
      // 拿到数组里面的所有三级联动的节点数组
      let pathNodes = arr[0].pathNodes

      // 获取中文地名
      let add = []
      pathNodes.forEach(el => {
        add.push(el.label)
      })
      // console.log(add)
      // 赋值中文地名给属性变量
      this.editForm.waterInstallAddress = add.join('-')
    },
    level_1(val) {
      // console.log(val)
      let regionArr = []
      let idArr = []
      val.forEach(el => {
        // 这个对象的属性，和defaultProps的配置有关联，label对应的值，要是这个对象里面的地名的属性
        // level属性，用来判断是几级地域
        let obj = { id: el.regionId, regionName: el.regionName, level: 1 }
        regionArr.push(obj)
        idArr.push(el.regionId)
      })
      this.data = regionArr
      this.defaultExpandedKeys = idArr
    }
  },
  methods: {
    // 合同
    contractHandler(path) {
      if (path) {
        console.log('查看')
        window.open(this.imgUrl + path, '', 'width=100%')
      } else {
        console.log('上传')
      }
    },
    // 获取计费类型，----》需要改为基本价格设置的类型
    getBillingTypeHandler() {
      getBilingBasePriceNotPage().then(res => {
        console.log('getBilingBasePriceNotPage', res)
        let newArr = []
        if (res.code === 200) {
          let arr = res.data
          arr.forEach(el => {
            newArr.push(el.billing)
          })
          this.billingType = newArr
        } else {
          this.$message({
            message: '获取计费类型失败',
            type: 'error'
          })
        }
      })
    },
    // 获取一个节点的子级
    getChildReginHandler(id) {
      return queryChildrenRegionAll({ regionParentId: id }).then(res => {
        // console.log(res)
        if (res.code === 200) {
          return res.data
        }
      })
    },
    // 动态加载子tree
    loadNode(node, resolve) {
      console.log(node)
      this.getChildReginHandler(node.data.id).then(res => {
        console.log(res)
        let level = node.data.level + 1
        let regionArr = []
        let leaf = false
        level === 3 && (leaf = true)
        res.forEach(el => {
          let obj = { id: el.regionId, regionName: el.regionName, level, leaf }
          regionArr.push(obj)
        })
        console.log(regionArr)
        resolve(regionArr)
      })
    },
    // 选择1、2级别的地域时触发
    handleCheck(vlue) {
      console.log(vlue) // [6,7]
    },
    // 选中或清除选择的地域时触发的事件函数
    handleChange(value) {
      console.log(value) // 返回：[1,2,14]
    },
    // 查询所有根地域
    queryRootRegionAllHandler() {
      queryRootRegionAll().then(res => {
        if (res.code === 200) {
          console.log(res)
          this.level_1 = res.data
        } else {
          this.$message({
            message: '查询根地域失败',
            type: 'error'
          })
        }
      })
    },
    getUserFormatDate(v) {
      return getUserFormatDate(v)
    },
    // 获取一个水表的所有信息
    getWaterMeterDetail() {
      getWaterMeterDetailInfo({ waterNumber: this.waterNumber }).then(res => {
        if (res.code === 200) {
          console.log(res)

          this.waterInfo = {
            associatedList: res.data.associatedList,
            ...res.data.billingBasePrice,
            ...res.data.customer,
            ...res.data.waterMeter,
            ...res.data.waterType
          }

          this.waterId = this.waterInfo.waterId

          this.editForm.waterInstallAddress = this.waterInfo.waterInstallAddress
          this.editForm.waterInstallAddressInfo = this.waterInfo.waterInstallAddressInfo
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
        }
      })
    },
    //解除关联人员
    dissociatedHandle(row) {
      disAssociated({ associatedId: row.associatedId })
        .then(res => {
          if (res.code === 200) {
            this.$message({ message: res.msg, type: 'success' })
            this.getWaterMeterDetail()
          } else {
            this.$message({ message: res.msg, type: 'error' })
          }
        })
        .catch()
    },
    // 添加联系人
    addAssociatedHandler(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // 添加水表联系人
          addAssociated({ ...this.addAssociatedForm, waterId: Number(this.waterId) }).then(res => {
            console.log(res)
            if (res.code === 200) {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              this.isShowAssociated = false
              this.getWaterMeterDetail()
            } else {
              this.$message({
                message: res.msg,
                type: 'error'
              })
            }
          })
        } else {
          return false
        }
      })
    },
    showEditWaterMeterModal() {
      this.isShowEditWaterMeter = true
      this.editForm = {
        billingId: this.waterInfo.billingId,
        waterInstallAddress: this.waterInfo.waterInstallAddress,
        waterInstallAddressInfo: this.waterInfo.waterInstallAddressInfo,
        changeInfo: '',
        customerAddress: this.waterInfo.waterInstallAddress
      }
    },
    // 编辑水表信息,
    editEditWaterHandler(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // 编辑水表
          editWaterMeterInfo({
            billingId: Number(this.editForm.billingId),
            changeInfo: this.editForm.changeInfo,
            addressInfo: this.editForm.waterInstallAddressInfo,
            address: this.checkedAddessValues[2],
            waterId: Number(this.waterId)
          }).then(res => {
            console.log(res)
            if (res.code === 200) {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              this.isShowEditWaterMeter = false
              this.$refs.editform.resetFields()
              this.getWaterMeterDetail()
            } else {
              this.$message({
                message: res.msg,
                type: 'error'
              })
            }
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style></style>
